import time

from zz import zz_code, zz_dingtalk, zz_return, zz_log, zz_str
import requests
import json

log = zz_log.of()


def run():
    """
    token格式
    token@member_id@openid;token2@member_id2@openid2
    """
    token = zz_code.env("CHEANGTOU_TOKEN")
    token_arr = zz_str.split2(token)
    if len(token_arr) <= 0:
        log.error('未配置CHEANGTOU_TOKEN')
        return
    log.info(token_arr)

    log_msg = '**诚投签到** \n\n'
    for item in token_arr:
        openid = None
        if len(item) > 2:
            openid = item[2]
        print(item)
        handle = Handle(item[0], item[1], openid)

        log_msg_one = handle.run_one()
        log.info(log_msg_one)
        log_msg += log_msg_one + "\n\n"
        time.sleep(1)

    zz_dingtalk.send_markdown(log_msg, "诚投签到")


# 诚投
class Handle:
    def __init__(self, access_token, member_id, openid=None):
        self.access_token = access_token
        self.member_id = member_id
        self.app_key = '81c09e3069a2d443fe5fd0243ce023db'
        self.openid = openid

    def run_one(self):
        if zz_str.is_null_or_empty(self.access_token) or zz_str.is_null_or_empty(
                self.member_id):
            return "缺少参数"

        log_msg = self.member_id + "\n\n"
        r = self.api_qian()
        if r.err():
            log_msg += f"签到：{r.get_errmsg()}"
            return log_msg

        r = self.api_browse('2530819446751449117')
        if r.ok():
            log_msg += f"浏览任务1：完成\n\n"
        time.sleep(2)
        r = self.api_browse('2525284209070003236')
        if r.ok():
            log_msg += f"浏览任务2：完成\n\n"

        time.sleep(1)
        r = self.api_qian_check()
        fun = 0
        name = ''
        if r.ok():
            data = r.get_data('data')
            name = data['nickName']
            fun = data['availablePoints']

        log_msg += f"**{name}**, 签到成功，积分：{fun}"
        return log_msg

    def get_headers(self):
        headers = {
            "Application-Key": self.app_key,
            "Access-Token": self.access_token,
        }
        user_agent = zz_code.env("USER_AGENT")
        if zz_str.has_any_text(user_agent):
            headers['User-Agent'] = user_agent

        return headers

    # 签到
    def api_qian(self):
        api_url = f"https://gzct.gzccic.com/api/member/v1/signInMember/{self.member_id}"
        r = zz_return.of(123456)
        headers = self.get_headers()

        post_data = {
            "memberId": self.member_id,
            "yearMonth": zz_code.date_tostring(format='%Y-%m')
        }

        log.debug(api_url)
        log.debug(headers)
        log.debug(post_data)
        res = requests.post(api_url, json=post_data, headers=headers)
        r = self.to_return(res.content)

        return r

        return r

    # 查积分
    def api_qian_check(self) -> zz_return.Return:
        api_url = f"https://gzct.gzccic.com/api/member/v1/member-info/applet/member-info/{self.member_id}"
        r = zz_return.of(123456)
        headers = self.get_headers()

        log.debug(f"api_url: {api_url}")
        log.debug(f"headers: {headers}")
        res = requests.get(api_url, headers=headers)
        r = self.to_return(res.content)

        return r

    def api_browse(self, business_id):
        """
        浏览任务
        @param business_id: 任务ID
        """

        if zz_str.is_null_or_empty(self.openid):
            return zz_return.of(20117, "未配置openid，不执行浏览任务")

        api_url = f"https://gzct.gzccic.com/api/icommerce-mgmt/v1/app/advertisement/award/trigger"
        headers = self.get_headers()

        begin_time = zz_code.date_sub_second(zz_code.date_now(), 10)
        remark = {
            "beginTime": zz_code.date_tostring(begin_time),
            "endTime": zz_code.date_tostring(),
        }
        post_data = {
            "event": "BROWSE_HOUSE",
            "businessId": business_id,
            "duration": 10,
            "remark": json.dumps(remark),
            "openId": self.openid,
        }

        log.debug(api_url)
        log.debug(headers)
        log.debug(post_data)
        res = requests.post(api_url, json=post_data, headers=headers)
        r = self.to_return(res.content)

        return r

    def to_return(self, content) -> zz_return.Return:
        log.debug(content)
        try:
            r = zz_return.parse(content)
            errcode = r.get_data('resultCode')
            errmsg = r.get_data('resultMsg')
            r.set_errmsg(errmsg)
            r.set_errcode(errcode)
        except Exception as ex:
            log.error(ex)
            r = zz_return.of(123456, ex)
        log.info(f"return: {r.to_json()}")

        return r


if __name__ == '__main__':
    # 数据拼接
    data = [
        [
            'eyJhbGciOiJIUzI1NiJ9.eyJpbnN0YW5jZUlkIjoxNTUwNzY1NDA2NjA4ODc1MzMzLCJuaWNrTmFtZSI6IuWwj-WfjmNmdkxQalNDIiwibG9naW5OYW1lIjoiUjIwMjQwNDI4LTQ0MjErMDgwMDEiLCJkb21haW4iOiJkZWZhdWx0IiwidGVuYW50SWQiOjEsImlkIjoyNTI1NDcyODc2NjEwODQyNzA4LCJqdGkiOiJjZWM3YzJlMS02OWZiLTQ4NTItYmZiZC05YjBkOTEzYjI1ZjYiLCJuYmYiOjE3NTcwMjY4NzYsImV4cCI6MTc2MjIxODA3Nn0.V9h3hq1QrDvWFfWJq3Tl9t_IXJRso5Cej9RHwzvYtrY',
            '2525472877131970623',
            'o3y1-66d_13d7gz85lB6-DS7kfj0'
        ],
        [
            'eyJhbGciOiJIUzI1NiJ9.eyJpbnN0YW5jZUlkIjoxNTUwNzY1NDA2NjA4ODc1MzMzLCJuaWNrTmFtZSI6IuWwj-Wfjms0aDlkTlhiIiwibG9naW5OYW1lIjoiUjIwMjQwNzI3LTA1NDkrMDgwMDEiLCJkb21haW4iOiJkZWZhdWx0IiwidGVuYW50SWQiOjEsImlkIjoyNTMzNjI0MTc5Mzc1NTY4ODgzLCJqdGkiOiJmN2IyMWRiMy1kMTk1LTRhZjItOTM0Zi00ZDg4ZjgyMmQwMWIiLCJuYmYiOjE3NTcyOTAwNjQsImV4cCI6MTc2MjQ4MTI2NH0.9VmX2R4jETtGaTPj9oJ_gMV6qq7vsZRxcm1yc9R1qOA',
            '2533624179670271063',
            'o3y1-6yqrXrkErTqZ3z4pAnkaJaA'
        ],
        [
            'eyJhbGciOiJIUzI1NiJ9.eyJpbnN0YW5jZUlkIjoxNTUwNzY1NDA2NjA4ODc1MzMzLCJuaWNrTmFtZSI6IuWwj-WfjlpTdnVxMnRlIiwibG9naW5OYW1lIjoiUDIwMjQwNjE0LTAxNDIrMDgwMDEiLCJkb21haW4iOiJkZWZhdWx0IiwidGVuYW50SWQiOjEsImlkIjoyNTI5NzIwNzAxMDM3MzIwNzY0LCJqdGkiOiJiNmE3NjZmYy0zNzRkLTQ3NWUtOGNhZS01ZmRmMTBmMWQ4ZmQiLCJuYmYiOjE3NTA5MzQxMTgsImV4cCI6MTc1NjEyNTMxOH0.9vpaCkDy6M5FM1-2ay5oUyUkiSPH4tLxZ-_bd9UQ0As',
            '2529720701325678332',
            'o3y1-641OnMfoC5BX4sqIA9iCvQw'
        ],
    ]
    # print(zz_str.split2_from_list(data))
    run()
